//
//  ARRechargeCoinsViewModel.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/20.
//

import Foundation
import SwiftyStoreKit

class ARRechargeCoinsViewModel {
    
    private var _rechargeCoinsList: [ARRechargeCoinsModel] = []
    var rechargeCoinsList: [ARRechargeCoinsModel] {
        _rechargeCoinsList
    }
    
    func fetchRechargeCoinsList(_ completion: @escaping (Error?) -> Void) {
        ARFetchRechargeCoinsListRequest().fetchRechageCoinsList { [weak self] result in
            switch result {
            case .faild(let err):
                completion(err)
            case .successWithoutResponse:
                completion(ARRequestError.modelConvertError(error: nil))
            case .success(let model):
                self?._rechargeCoinsList.removeAll()
                self?._rechargeCoinsList.append(contentsOf: model)
                completion(nil)
            }
        }
    }
    
    func purchase(_ goodsCode: String, completion: @escaping (Error?) -> Void) {
        // 先创建订单
        ARCreateRechargeOrderRequest().createOrder(goodsCode) { [weak self] result in
            switch result {
            case .faild(let err):
                completion(err)
            case .successWithoutResponse:
                completion(ARRequestError.modelConvertError(error: nil))
            case .success(let model):
                // 成功 -> 内购
                self?.inAppPurchase(model, completion: completion)
            }
        }
    }
    
    private func inAppPurchase(_ model: ARRechargeOrderModel, completion: @escaping (Error?) -> Void) {
        SwiftyStoreKit.purchaseProduct(model.goodsCode) { [weak self] purchaseResult in
            switch purchaseResult {
            case .error(let error):
                completion(error)
            case .success(let purchase):
                // 成功 - 验证
                if purchase.needsFinishTransaction {
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                }
                self?.receiptVerification(order: model, purchaseDetail: purchase, completion: completion)
            }
        }
    }
    
    /// 验证
    private func receiptVerification(order: ARRechargeOrderModel, purchaseDetail: PurchaseDetails, completion: @escaping (Error?) -> Void) {
        
        func verify(_ receiptStr: String) {
            ARIAPReceiptVerificationRequest().verify(order.orderNo, payload: receiptStr, transcationId: purchaseDetail.transaction.transactionIdentifier ?? "") { err in
                if err == nil {
                    // 成功 -> 更新
                    NotificationCenter.default.post(name: .shouldUpdateUserInfo, object: nil)
                }
                completion(err)
            }
        }
        
        let receiptData = SwiftyStoreKit.localReceiptData
        if receiptData == nil {
            SwiftyStoreKit.fetchReceipt(forceRefresh: true) { result in
                switch result {
                case .success(let receiptData):
                    let receiptString = receiptData.base64EncodedString(options: [])
                    verify(receiptString)
                case .error(let error):
                    completion(error)
                }
            }
        } else {
            let receiptString = receiptData!.base64EncodedString(options: [])
            verify(receiptString)
        }
    }
}
